package com.zhugang.september;

import java.util.HashSet;
import java.util.Set;

/**
 * @program algorithms
 * @description: test
 * @author: chanzhugang
 * @create: 2021/09/21 22:01
 */
public class HasCycleList {

    /**
     * 遍历链表，hashSet
     */
    public boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }

    /**
     * 快慢指针: 龟兔赛跑赛跑算法
     * @param head
     * @return
     */
    public boolean hasCycl1(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }


    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}